package com.jfirer.mvc.resolver.impl;

import com.jfirer.baseutil.reflect.ReflectUtil;
import com.jfirer.mvc.annotation.PathVariable;
import com.jfirer.mvc.annotation.RequestMapping;
import com.jfirer.mvc.resolver.AbstractParamResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;

public class PathVariableResolver extends AbstractParamResolver
{
    private              int        start;
    private              int        end;
    private              Class      type;
    private static final Set<Class> permission = new HashSet<Class>();

    static
    {
        permission.add(Integer.class);
        permission.add(Byte.class);
        permission.add(Short.class);
        permission.add(Long.class);
        permission.add(Float.class);
        permission.add(Double.class);
        permission.add(Boolean.class);
        permission.add(Character.class);
        permission.add(String.class);
    }

    public PathVariableResolver(String paramName, Method method, int paramIndex)
    {
        super(paramName);
        Annotation[] parameterAnnotation = method.getParameterAnnotations()[paramIndex];
        Annotation   annotation          = parameterAnnotation[0];
        if (annotation instanceof PathVariable == false)
        {
            throw new IllegalArgumentException();
        }
        String         value          = ((PathVariable) annotation).value();
        RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
        String         url            = requestMapping.value();
        start = url.indexOf(value);
        end = url.indexOf("}", start);
        Class<?> parameterType = method.getParameterTypes()[paramIndex];
        if (parameterType.isPrimitive() || permission.contains(parameterType))
        {
            type = parameterType.isPrimitive() ? ReflectUtil.wrapPrimitive(parameterType) : parameterType;
        }
        else
        {
            throw new IllegalArgumentException("方法：" + method.toGenericString() + "第" + (paramIndex + 1) + "个参数不是基本类型，无法从路径中获取数据");
        }
    }

    @Override
    public Object resolve(HttpServletRequest request, HttpServletResponse response)
    {
        String requestURI   = request.getRequestURI();
        String pathVariable = requestURI.substring(start, end);
        return toValue(type, pathVariable);
    }
}
